package org.handsomezhi.shortlink.admin.util.interceptor;

import com.google.common.collect.Lists;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.handsomezhi.shortlink.admin.common.biz.user.UserContext;
import org.handsomezhi.shortlink.admin.common.convention.exception.ClientException;
import org.handsomezhi.shortlink.admin.config.UserFlowRiskControlConfiguration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Optional;

import static org.handsomezhi.shortlink.admin.common.enums.UserErrorCodeEnum.FLOW_LIMIT_ERROR;


@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;


    private static final String USER_FLOW_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";


    public LoginInterceptor(StringRedisTemplate stringRedisTemplate, UserFlowRiskControlConfiguration userFlowRiskControlConfiguration) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.userFlowRiskControlConfiguration = userFlowRiskControlConfiguration;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (UserContext.getUser() == null) {
            response.setStatus(401);
            return false;
        }


        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_CONTROL_LUA_SCRIPT_PATH)));
        redisScript.setResultType(Long.class);
        String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");

        if (userFlowRiskControlConfiguration != null && userFlowRiskControlConfiguration.getEnable()) {
            Long result = null;
            try {
                result = stringRedisTemplate.execute(redisScript, Lists.newArrayList(username), userFlowRiskControlConfiguration.getTimeWindow());
            } catch (Throwable ex) {
                log.error("将执行用户请求流量限制LUA脚本出错", ex);
                throw new ClientException(FLOW_LIMIT_ERROR);
            }
            if (result == null || result > userFlowRiskControlConfiguration.getMaxAccessCount()) {
                throw new ClientException(FLOW_LIMIT_ERROR);
            }
        }
        return true;
    }

}
